<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogDetail.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogDetail.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    @close="closeDialog(false)"
  >
    <el-row v-loading="loading" :gutter="20">
      <el-col v-if="dialogDetail.type != 1" :span="auditSpan" :offset="0">
        <el-timeline v-if="auditLog && auditLog.length > 0">
          <el-timeline-item v-for="item in auditLog" :key="item.id" :timestamp="item.createTime" placement="top">
            <el-card style="padding: 5px">
              <div style="font-weight: bold; font-size: 14px">
                {{ item.flowEngineName }}
                &nbsp;
                <el-tag v-if="item.auditStatus !== -1" :type="item.auditStatus === 1 ? 'primary' : 'info'">{{
                  item.auditStatusName
                }}</el-tag>
                &nbsp;
                <el-tag v-if="item.auditIdea !== 0" :type="item.auditIdea === 1 ? 'success' : 'error'">{{
                  item.auditIdeaName
                }}</el-tag>
              </div>
              <p style="text-indent: 1em; line-height: 10px">{{ item.auditIdeaContent }}</p>
              <p style="text-indent: 1em; line-height: 10px">{{ item.auditTime }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <el-empty v-else description="暂未审核记录" />
      </el-col>
      <el-col :span="detailSpan" :offset="0">
        <el-descriptions title="工资信息" :column="3">
          <el-descriptions-item label="劳务公司">{{ detailInfo.corpName }}</el-descriptions-item>
          <el-descriptions-item label="总支出额">{{ detailInfo.totalExpenditure }}</el-descriptions-item>
          <el-descriptions-item label="发放月份">{{ detailInfo.month }}</el-descriptions-item>
          <el-descriptions-item label="当月应考勤天数">{{ detailInfo.days }}</el-descriptions-item>
          <el-descriptions-item label="当月计价">{{ detailInfo.totalValuation }}</el-descriptions-item>
          <el-descriptions-item label="剩余合同金额">{{ detailInfo.remainingAmount }}</el-descriptions-item>
          <el-descriptions-item label="代发凭证" :span="3">
            <div v-for="item in detailInfo.attachments" :key="item.attachmentId" @click="download(item.attachmentId)">
              <el-link type="primary">{{ item.attachmentName }}</el-link>
            </div></el-descriptions-item
          >

          <el-descriptions-item :span="3">
            <el-form ref="formRef" v-loading="loading" :model="detailInfo" :rules="rules">
              <el-table
                :data="detailInfo.details"
                style="width: 100%; margin-bottom: 20px"
                row-key="uid"
                show-summary
                :span-method="objectSpanMethod"
                :row-class-name="tableRowClassName"
                border
                default-expand-all
                :height="370"
              >
                <el-table-column prop="groupName" label="劳务班组" width="100" />
                <el-table-column prop="personName" label="姓名" width="80">
                  <template #default="scope">
                    <span
                      v-if="scope.row.personName === '班组总计'"
                      style="font-weight: bold; position: absolute; right: 10px; top: 30%"
                      >{{ scope.row.personName }}</span
                    >
                    <label v-else>{{ scope.row.personName }}</label>
                  </template>
                </el-table-column>
                <el-table-column prop="idCard" label="身份证号" />
                <el-table-column prop="bankName" label="开户行" />
                <el-table-column prop="personBankNo" label="银行卡号" />
                <el-table-column prop="attendanceDays" label="实际考勤天数" width="130" sortable />
                <el-table-column prop="amountApplied" label="申请发放金额" width="130" sortable>
                  <template v-if="dialogDetail.type == 1" #default="scope">
                    <el-form-item v-if="scope.row.personName === '班组总计'">
                      <el-input v-model="scope.row.amountApplied" type="number" :readonly="true" />
                    </el-form-item>
                    <el-form-item
                      v-else
                      :prop="`details[${scope.row.parentNum - 1}].children[${scope.row.childrenNum}]['amountApplied']`"
                      :rules="rules.amountApplied"
                    >
                      <el-input
                        v-model="scope.row.amountApplied"
                        type="number"
                        :readonly="scope.row.personName === '班组总计'"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column v-if="dialogDetail.type == 1" label="操作" fixed="right" width="80">
                  <template #default="scope">
                    <el-button type="primary" link size="small" @click="handleDelete(scope.row)">
                      <i-ep-delete />
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
      <el-col v-if="dialogDetail.type == 2" :span="18" :offset="6">
        <el-form ref="auditFormRef" :model="auditFormData" label-width="80" :rules="auditRules">
          <el-form-item label="审核意见" prop="auditIdea" style="margin-bottom: 18px">
            <el-checkbox
              v-model="yesChecked"
              label="通过"
              @change="
                (value: boolean) => {
                  if (value) {
                    auditFormData.auditIdea = 1;
                    noChecked = false;
                  } else auditFormData.auditIdea = undefined;
                }
              "
            />
            <el-checkbox
              v-model="noChecked"
              label="不通过"
              @change="
                (value: boolean) => {
                  if (value) {
                    auditFormData.auditIdea = -1;
                    yesChecked = false;
                  } else auditFormData.auditIdea = undefined;
                }
              "
            />
          </el-form-item>
          <el-form-item label="" prop="auditIdeaContent" style="margin-bottom: 18px">
            <el-input v-model="auditFormData.auditIdeaContent" type="textarea" :rows="3"></el-input>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col v-if="dialogDetail.type == 3" :span="18" :offset="6">
        <el-form ref="submitFormRef" :model="submitFormData" label-width="80" :rules="submitRules">
          <el-form-item label="上传凭证" prop="attachments" style="margin-bottom: 18px">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <template v-if="dialogDetail.type != 0" #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogDetail.footBtn }} </el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { useScreen } from "@/store/modules/screen";
import { AuditPayroll, QueryAuditLogs, PayrollDetail, AddPayrollDetail, SubmitPayroll } from "@/api/wage/index";
import { getVerificationCode } from "@/api/account/project/index";
import { AuditForm, PayrollDetailEditForm } from "@/api/wage/types";
import { FormRules } from "element-plus/es/components/form/src/types";
import { ElButton, ElFormItem, ElInput, UploadUserFile } from "element-plus";
import { downloadFile } from "@/utils";
import { downloadAttachment } from "@/api/common/other/index";

const download = (id: string) => {
  downloadAttachment(id).then((res) => {
    downloadFile(res);
  });
};

//声明变量
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);

//上传文件列表
const fileList = ref<UploadUserFile[]>([]);
//提交表单
const submitFormData = reactive({
  attachments: new Array<any>(),
});
const submitFormRef = ref();
const submitRules = reactive({
  attachments: [
    {
      required: true,
      trigger: "change",
      validator: (rule: any, value: any, callback: any) => {
        if (fileList.value.length == 0) {
          callback(new Error("请上传代发凭证"));
        }
        if (fileList.value.indexOf((i) => i.status != "success") > -1) {
          callback(new Error("请等待上传完成"));
        }
        callback();
      },
    },
  ],
});

const currentSystem = ref(localStorage.getItem("usertypeName"));
const isLumpContractor = ref(localStorage.getItem("isLumpContractor"));
const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(1200);
const detailSpan = ref(24);
const auditSpan = ref(24);
const props = defineProps({
  dialogDetail: {
    type: Object,
    default: () => ({
      visible: false,
      title: "详情",
      footBtn: "详情",
      id: 0,
      type: 0, //0: 详情 1: 工资明细 2: 审核 3:提交
    }),
  },
});
const { dialogDetail } = toRefs(props);
const emit = defineEmits(["sendClose"]);
const loading = ref(false);
const auditFormRef = ref();
const auditFormData = reactive<AuditForm>({});
const auditRules = reactive<FormRules<AuditForm>>({
  auditIdea: [
    {
      required: true,
      message: "请选择审核意见",
      trigger: "change",
    },
  ],
  auditIdeaContent: [
    {
      required: true,
      message: "请输入审核意见内容",
      trigger: "change",
    },
  ],
});

const yesChecked = ref(false);
const noChecked = ref(false);

//工资信息
const detailInfo = ref({} as any);
//审核日志
const auditLog = ref([] as any[]);
const formRef = ref();
const rules = {
  amountApplied: [{ required: true, message: "", trigger: "blur" }],
};

//合并列
const objectSpanMethod = (data: { row: any; column: any; rowIndex: number; columnIndex: number }) => {
  if (data.columnIndex === 0) {
    if (data.row.fold) {
      data.row.groupName = "";
      return {
        rowspan: data.row.rowspan,
        colspan: 1,
      };
    } else {
      if (data.row.foldChildren) {
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }
  }
};

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};
//行样式
const tableRowClassName = (data: { row: any; rowIndex: number }) => {
  if (data.row.personName === "班组总计") {
    data.row.amountApplied = data.row.children.reduce((prev: number, next: { amountApplied: any }) => {
      return prev + Number(next.amountApplied);
    }, 0);

    data.row.attendanceDays = data.row.children.reduce((prev: number, next: { attendanceDays: any }) => {
      return prev + Number(next.attendanceDays);
    }, 0);
    return "warning-row";
  }
  return "";
};

//删除明细
const handleDelete = (row: any) => {
  if (row.personName === "班组总计") {
    let tempData = detailInfo.value.details.filter((item: any) => item.uid !== row.uid);
    detailInfo.value.details = Object.assign([], tempData);
    resetDetails();
    return;
  }
  let uid = row.uid;
  detailInfo.value.details.map((item: { children: any[] }) => {
    item.children.forEach((i: { uid: any; fold: any }, index: number) => {
      if (i.uid === uid) {
        if (i.fold) {
          if (item.children[index + 1] && item.children.length > 0) {
            item.children[index + 1].fold = true;
            item.children[index + 1].rowspan = item.children[0].rowspan - 1;
          }
        } else {
          item.children[0].rowspan = item.children[0].rowspan - 1;
        }
        item.children.splice(index, 1);
      }
    });
  });
  resetDetails();
};

//重新计算Details
const resetDetails = () => {
  if (detailInfo.value.details && detailInfo.value.details.length > 0) {
    detailInfo.value.details.map((item: any, itemIndex: number) => {
      item.children.map((child: any, childIndex: number) => {
        child.parentNum = itemIndex + 1;
        child.childrenNum = childIndex;
      });
    });
    console.log(detailInfo.value.details);
  }
};

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
  } else {
    screenWidth.value = 1300;
    detailSpan.value = 18;
    auditSpan.value = 6;
    if (dialogDetail.value.type == 1) {
      detailSpan.value = 24;
    }
  }
}
const GenNonDuplicateID = () => {
  let idStr = Date.now().toString(36);
  idStr += Math.random().toString(36).substr(3);
  return idStr;
};
const resolveTableData = () => {
  let tempFirst = [] as any[];
  if (detailInfo.value.details && detailInfo.value.details.length > 0) {
    detailInfo.value.details.map(
      (item: {
        groupName: any;
        projectName: any;
        personName: any;
        idCard: any;
        bankName: any;
        personBankNo: any;
        attendanceDays: any;
        amountApplied: any;
        uid: string;
        foldChildren: boolean;
        parentNum: any;
        childrenNum: number;
      }) => {
        if (tempFirst && tempFirst.length < 1) {
          tempFirst.push({
            groupName: item.groupName,
            uid: GenNonDuplicateID(),
            personName: "班组总计",
            amountApplied: 0,
            children: [
              {
                uid: GenNonDuplicateID(),
                fold: true,
                rowspan: 1,
                parentNum: 1,
                childrenNum: 0,
                projectName: item.projectName,
                groupName: item.groupName,
                personName: item.personName,
                idCard: item.idCard,
                bankName: item.bankName,
                personBankNo: item.personBankNo,
                attendanceDays: item.attendanceDays,
                amountApplied: item.amountApplied,
              },
            ],
          });
        } else {
          if (
            tempFirst.every((team) => {
              return team.groupName !== item.groupName;
            })
          ) {
            tempFirst.push({
              groupName: item.groupName,
              uid: GenNonDuplicateID(),
              personName: "班组总计",
              amountApplied: 0,
              children: [
                {
                  uid: GenNonDuplicateID(),
                  fold: true,
                  rowspan: 1,
                  parentNum: tempFirst.length + 1,
                  childrenNum: 0,
                  projectName: item.projectName,
                  groupName: item.groupName,
                  personName: item.personName,
                  idCard: item.idCard,
                  bankName: item.bankName,
                  personBankNo: item.personBankNo,
                  attendanceDays: item.attendanceDays,
                  amountApplied: item.amountApplied,
                },
              ],
            });
          } else {
            tempFirst.map((temp) => {
              if (temp.groupName === item.groupName) {
                item.uid = GenNonDuplicateID();
                item.foldChildren = true;
                temp.children[0].rowspan++;
                item.parentNum = temp.children[0].parentNum;
                item.childrenNum = temp.children[0].rowspan - 1;
                temp.children.push(item);
              }
            });
          }
        }
      }
    );
  }
  detailInfo.value.details = tempFirst;
};
const initForm = function () {
  if (dialogDetail.value.id) {
    loading.value = true;
    let loadCount = 0;
    //初始化审核日志
    QueryAuditLogs(props.dialogDetail.id)
      .then((res) => {
        if (res.type == 0) {
          if (res.success) {
            auditLog.value = res.data;
          } else {
            ElMessage({
              type: "error",
              message: res.msg,
            });
          }
        } else {
          ElMessage({
            type: "error",
            message: res.msg,
          });
        }
      })
      .finally(() => {
        loadCount++;
        loadCount === 2 && (loading.value = false);
      });
    //初始化工资信息
    PayrollDetail(dialogDetail.value.id)
      .then((res) => {
        if (res.type == 0) {
          if (res.success) {
            detailInfo.value = res.data;
            resolveTableData();
          } else {
            ElMessage({
              type: "error",
              message: res.msg,
            });
          }
        } else {
          ElMessage({
            type: "error",
            message: res.msg,
          });
        }
      })
      .finally(() => {
        loadCount++;
        loadCount === 2 && (loading.value = false);
      });
  }
};

onMounted(async () => {
  initScreen();
  initForm();
});

//提交审核
const handleSubmit = async () => {
  if (dialogDetail.value.type == 1) {
    if (!detailInfo.value.details || detailInfo.value.details.length < 1) {
      ElMessage({
        type: "error",
        message: "工资单不能为空！",
      });
      return;
    }
    formRef.value.validate((valid: any) => {
      if (valid) {
        loading.value = true;
        let temp = new Array<PayrollDetailEditForm>();
        detailInfo.value.details.forEach((item: any) => {
          item.children.forEach((i: any) => {
            let te = Object.assign({}, i);
            te.groupName = item.groupName;
            temp.push(te);
            te = null;
          });
        });
        AddPayrollDetail(props.dialogDetail.id, temp)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog(true);
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        ElMessage.warning("请检查表单输入信息!");
      }
    });
  } else if (dialogDetail.value.type == 2) {
    auditFormRef.value.validate((valid: any) => {
      if (valid) {
        //不需要验证手机号直接审核
        if (!detailInfo.value.needVerify) {
          handleAuditPayroll();
          return;
        }
        //需要验证手机号的情况下验证手机号后调用审核
        const verifyCodeForm = ref({
          code: "",
        });
        const verifyCodeBtnStr = ref("获取验证码");
        const disabledVerifyCodeBtn = ref(false);
        const countDown = ref(60);
        const countDownInterval = ref();
        ElMessageBox({
          title: `审核验证,核实人:${detailInfo.value.verifyName}(${detailInfo.value.verifyMobile})`,
          message: () =>
            h("div", [
              h(
                ElForm,
                {
                  model: verifyCodeForm,
                  labelWidth: "80px",
                },
                [
                  h(
                    ElFormItem,
                    {
                      rules: [
                        {
                          required: true,
                          message: "请输入验证码",
                        },
                      ],
                      label: "验证码",
                      prop: "code",
                    },
                    [
                      h(ElInput, {
                        modelValue: verifyCodeForm.value.code,
                        placeholder: "请输入验证码",
                        onInput: (value: any) => {
                          verifyCodeForm.value.code = value;
                        },
                        style: {
                          width: "200px",
                        },
                      }),
                      h(
                        ElButton,
                        {
                          type: "success",
                          style: {
                            marginLeft: "5px",
                          },
                          disabled: disabledVerifyCodeBtn.value,
                          onClick() {
                            GetVerifyCode();
                            disabledVerifyCodeBtn.value = true;
                            countDown.value = 59;
                            verifyCodeBtnStr.value = countDown.value + "s后重试";
                            countDownInterval.value = setInterval(() => {
                              if (countDown.value <= 0) {
                                clearInterval(countDownInterval.value);
                                disabledVerifyCodeBtn.value = false;
                                verifyCodeBtnStr.value = "获取验证码";
                                countDown.value = 60;
                              } else {
                                verifyCodeBtnStr.value = countDown.value + "s后重试";
                                countDown.value--;
                              }
                            }, 1000);
                          },
                        },
                        [verifyCodeBtnStr.value]
                      ),
                    ]
                  ),
                ]
              ),
            ]),
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          showCancelButton: true,
          beforeClose(action, instance, done) {
            if (action === "confirm") {
              if (verifyCodeForm.value.code) {
                instance.confirmButtonLoading = true;
                instance.confirmButtonText = "执行中...";
                auditFormData.verifyCode = verifyCodeForm.value.code;
                handleAuditPayroll(done);
              } else {
                ElMessage.warning("请检查验证码输入");
              }
            } else {
              done();
            }
          },
        });
        //handleAuditPayroll();
      }
    });
  } else if (dialogDetail.value.type == 3) {
    let valid = await submitFormRef.value.validate();
    if (!valid) return;
    loading.value = true;
    submitFormData.attachments = [];
    fileList.value.forEach((item: any) => {
      if (item.status == "success") {
        submitFormData.attachments.push({
          attachmentId: item.response.data,
        });
      }
    });
    let res = await SubmitPayroll(dialogDetail.value.id, submitFormData.attachments);
    loading.value = false;
    if (res.type == 0 && res.success) closeDialog(true);
  }
};

//审核工资单
const handleAuditPayroll = (callback?: any) => {
  loading.value = true;
  AuditPayroll(dialogDetail.value.id, auditFormData)
    .then((res) => {
      if (res.type == 0) {
        if (res.success) {
          ElMessage({
            type: "success",
            message: res.msg,
          });
          closeDialog(true);
        } else {
          ElMessage({
            type: "error",
            message: res.msg,
          });
        }
      }
    })
    .finally(() => {
      loading.value = false;
      callback();
    });
};

const GetVerifyCode = async () => {
  let result = await getVerificationCode(detailInfo.value.verifyMobile ?? "");
  if (result.success) {
    ElMessage.success("验证码发送成功!");
  }
};

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
}
</script>

<style lang="scss" scoped>
:deep(.el-timeline) {
  height: 500px;
  overflow: hidden;
  scrollbar-width: none;
}
:deep(.el-timeline:hover) {
  overflow: auto;
}
::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}
:deep(.el-form-item) {
  margin-bottom: 0;
}
:deep(.el-textarea) {
  margin: 0;
}
</style>
